package com.lc.YYGH.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.lc.YYGH.oss.service.FileService;
import com.lc.YYGH.oss.utils.ConstantOssPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(MultipartFile file) {
       String endpoint= ConstantOssPropertiesUtil.ENDPOINT;
       String accessKeyId=ConstantOssPropertiesUtil.ACCESS_KEY_ID;
       String accessKeySecret=ConstantOssPropertiesUtil.SECRET;
       String bucketName=ConstantOssPropertiesUtil.BUCKET;
       OSS ossClient=new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        InputStream inputStream=null;
       try {
            inputStream=file.getInputStream();
            String fileName=file.getOriginalFilename();
            String uuid= UUID.randomUUID().toString().replaceAll("-","");
            fileName=uuid+fileName;
            String timeUrl=new DateTime().toString("yyyy/MM/dd");
            fileName=timeUrl+"/"+fileName;


           ossClient.putObject(bucketName,fileName,inputStream);
           //上传后得到文件路径
           String url=String.format("https://%s.%s/%s",bucketName,endpoint,fileName);
           return url;
        } catch (IOException e) {
            e.printStackTrace();

        }
       ossClient.shutdown();
       return "";

    }
}
